<template>
	<view>
		<view class="title">个人身体健康状况表</view>
		<canvas canvas-id="bar" id="bar" type="2d" class="charts" @touchstart="touchstart" @touchmove="touchmove"
			@touchend="touchend" />
	</view>
</template>

<script>
import uCharts from '@/uni_modules/qiun-data-charts/js_sdk/u-charts/u-charts.js';
var uChartsInstance = {};
export default {
	data() {
		return {
			cWidth: 750,
			cHeight: 500,
			pixelRatio: 2,
		};
	},
	onReady() {
		//这里的 750 对应 css .charts 的 width
		this.cWidth = uni.upx2px(750);
		//这里的 500 对应 css .charts 的 height
		this.cHeight = uni.upx2px(500);
		this.pixelRatio = uni.getSystemInfoSync().pixelRatio;
		this.getServerData();
	},
	methods: {
		getServerData() {
			//模拟从服务器获取数据时的延时
			setTimeout(() => {
				//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
				let res = {
					categories: ["血压", "血脂", "血糖", "心率", "总胆固醇", "甘油三酯"],
					series: [
						{
							name: "您的指标",
							data: [35, 36, 31, 33, 13, 34]
						},
						{
							name: "同龄指标",
							data: [68, 27, 21, 24, 6, 28]
						}
					]
				};
				this.drawCharts('bar', res);
			}, 500);
		},
		drawCharts(id, data) {
			const query = uni.createSelectorQuery().in(this);
			query.select('#' + id).fields({ node: true, size: true }).exec(res => {
				if (res[0]) {
					const canvas = res[0].node;
					const ctx = canvas.getContext('2d');
					canvas.width = res[0].width * this.pixelRatio;
					canvas.height = res[0].height * this.pixelRatio;
					uChartsInstance[id] = new uCharts({
						type: "column",
						context: ctx,
						width: this.cWidth * this.pixelRatio,
						height: this.cHeight * this.pixelRatio,
						categories: data.categories,
						series: data.series,
						pixelRatio: this.pixelRatio,
						animation: true,
						background: "#FFFFFF",
						color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
						padding: [15, 15, 0, 5],
						touchMoveLimit: 24,
						enableScroll: true,
						legend: {},
						xAxis: {
							disableGrid: true,
							scrollShow: true,
							itemCount: 4
						},
						yAxis: {
							data: [
								{
									min: 0
								}
							]
						},
						extra: {
							column: {
								type: "group",
								width: 30,
								activeBgColor: "#000000",
								activeBgOpacity: 0.08
							}
						}
					});
				} else {
					console.error("[uCharts]: 未获取到 context");
				}
			});
		},
		touchstart(e) {
			uChartsInstance[e.target.id].scrollStart(e);
		},
		touchmove(e) {
			uChartsInstance[e.target.id].scroll(e);
		},
		touchend(e) {
			uChartsInstance[e.target.id].scrollEnd(e);
			uChartsInstance[e.target.id].touchLegend(e);
			uChartsInstance[e.target.id].showToolTip(e);
		}
	}
};
</script>

<style scoped>
.charts {
	width: 750rpx;
	height: 500rpx;
}

.title {
	text-align: center;
	line-height: 50px;
	font-size: 25px;
}
</style>